#include "rolemanager.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QUuid>
#include <QDebug>

RoleManager::RoleManager(QObject *parent) : QObject(parent)
{
}

bool RoleManager::loadRoles(const QString &filePath)
{
    if (!QFile::exists(filePath)) {
            QFile file(filePath);
            if (file.open(QIODevice::WriteOnly)) {
                file.write("[]"); // 空JSON数组
                file.close();
            }
        }
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Could not open roles file:" << filePath;
        return false;
    }

    QByteArray data = file.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);

    //    if (doc.isNull() || !doc.isArray())
    if (!doc.isArray())
    {
        qWarning() << "Invalid JSON format in roles file";
        return false;
    }

    m_roles.clear();
    QJsonArray rolesArray = doc.array();

    for (const QJsonValue &value : rolesArray) {
        QJsonObject roleObj = value.toObject();
        Role role;
        role.id = roleObj["id"].toString();
        role.name = roleObj["name"].toString();
        role.description = roleObj["description"].toString();
        role.prompt = roleObj["prompt"].toString();
        m_roles.append(role);
    }

    return true;
}

QVector<Role> RoleManager::getRoles() const
{
    return m_roles;
}

Role RoleManager::getRoleById(const QString &id) const
{
    for (const Role &role : m_roles) {
        if (role.id == id) {
            return role;
        }
    }
    return Role(); // 返回空角色
}

bool RoleManager::saveCustomRole(const QString &name, const QString &prompt, const QString &description)
{
    QString dirPath = QDir::currentPath() + "/KyAiData";
    QDir dir(dirPath);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            qDebug() << "创建目录失败" << dirPath;
        }
    }
    QFile file(QDir::currentPath() +"/KyAiData/custom_roles.json");
    // 读取现有角色或创建新数组
    QJsonArray rolesArray;
    if (file.exists() && file.open(QIODevice::ReadOnly)) {
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        if (!doc.isNull() && doc.isArray()) {
            rolesArray = doc.array();
        }
        file.close();
    }
    // 创建新角色对象
    QJsonObject newRole;
    newRole["id"] = QUuid::createUuid().toString();
    newRole["name"] = name;
    newRole["prompt"] = prompt;
    newRole["description"] = description;
    rolesArray.append(newRole);

    // 写入文件
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        qWarning() << "Failed to open custom roles file for writing" ;
        return false;
    }

    file.write(QJsonDocument(rolesArray).toJson());
    file.close();

    // 重新加载角色
    return true;
}
